package com.hhh.tools.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import java.security.MessageDigest

class Md5ViewModel : ViewModel() {

    private var _input = MutableStateFlow("")
    val input: StateFlow<String> = _input

    private var _content = MutableStateFlow("")
    val content: StateFlow<String> = _content

    fun onInputChange(input: String) {
        _input.value = input

        if (input.isNotEmpty()) {
            _content.value = md5(input)
        } else {
            _content.value = ""
        }
    }

    /** md5加密 */
    private fun md5(content: String): String {
        val hash = MessageDigest.getInstance("MD5").digest(content.toByteArray())
        val hex = StringBuilder(hash.size * 2)
        for (b in hash) {
            var str = Integer.toHexString(b.toInt())
            if (b < 0x10) {
                str = "0$str"
            }
            hex.append(str.substring(str.length -2))
        }
        return hex.toString()
    }

}